const $ = (function () {
    const getParams = data => {
        let str = ''
        for (let key in data) {
            if (Array.isArray(data[key])) {
                data[key].forEach(el => {
                    str += key + '=' + el + '&'
                })
            } else {
                str += key + '=' + data[key] + '&'
            }
        }
        return str
    }

    const ajax = (options = {}) => {
        let sttings = { //默认参数
            type: 'get',
            async: true,
            dataType: 'json'
        }
        options = Object.assign(sttings, options)   //传入值会覆盖默认值
        let xhr = createXHR();
        if (options.type === 'get') {
            xhr.open(options.type, options.url + '?' + getParams(options.data), options.async)
            xhr.send(null)
        } else {
            xhr.open(options.type, options.url, options.async)
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.responseType = options.dataType;
            xhr.send(getParams(options.data))
        }

        if (options.async) {
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        if (typeof (options.success) == 'function') {
                            options.success(xhr.response)
                        }
                    }
                }
            }
        } else {
            if (xhr.status == 200) {
                if (typeof (options.success) == 'function') {
                    options.success(xhr.response)
                }
            }
        }
    }

    const JSONP = (options = {}) => {
        let fnName = 'JQ_' + Date.now();    //生成不重复函数名
        window[fnName] = options.success;
        let newUrl = options.url + '?' + getParams(options.data) + options.jsonp + '=' + fnName;
        let oScript = document.createElement('script');
        oScript.setAttribute('src', newUrl);
        document.body.appendChild(oScript);
        oScript.onload = function () {
            this.remove()
        }
    }
    return {
        ajax,
        JSONP
    }

})()